package com.yb7s.springboot.jdbc.controller;

import com.yb7s.springboot.jdbc.pojo.User;
import com.yb7s.springboot.jdbc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Date: 2019/3/3 12:50
 * @Auther: ybzhu
 * @Description：
 */
@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * 注入 user service
     */
    @Autowired
    private UserService userService;

    /**
     * 查询用户列表
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public List<User> getUsers(){
        return userService.findUserList();
    }

    /**
     * 查询一个用户
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public  User getUserById(@PathVariable("id") int id){
        return userService.findUserById(id);
    }
    /**
     * 删除一个用户
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public  String delUserById(@PathVariable("id") int id){
        int flag=userService.delete(id);
        if(flag==1){
            return "删除成功！";
        }else {
            return "删除失败！";
        }
    }

    /**
     * 修改用户信息
     * @param id
     * @param name
     * @param money
     * @return
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    public  String updateUser(@PathVariable("id")int id , @RequestParam(value = "name",required = true)String name,
                                 @RequestParam(value = "money" ,required = true)double money){
        User User=new User();
        User.setMoney(money);
        User.setName(name);
        User.setId(id);
        int t=userService.update(User);
        if(t==1){
            return "修改成功！";
        }else {
            return "修改失败！";
        }
    }

    /**
     * 新增用户信息
     * @param name
     * @param money
     * @return
     */
    @RequestMapping(value = "",method = RequestMethod.POST)
    public  String postUser( @RequestParam(value = "name")String name,
                                @RequestParam(value = "money" )double money){
        User User=new User();
        User.setMoney(money);
        User.setName(name);
        int t= userService.add(User);
        if(t==1){
            return "新增成功";
        }else {
            return "新增失败";
        }

    }
}
